package com.hxexp.weixin.common.jaxb;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactoryConfigurationError;

import org.xml.sax.SAXException;

import com.hxexp.weixin.common.string.StringHelper;
import com.qq.weixin.mp.api.pay.model.CommonParamJaxb;
import com.qq.weixin.mp.api.pay.model.UnifiedOrderParamJaxb;
import com.qq.weixin.mp.message.hxexp.model.send.BaseReplyJaxb;
import com.qq.weixin.mp.message.hxexp.model.send.ImageReplyJaxb;
import com.qq.weixin.mp.message.hxexp.model.send.NotifyResponseJaxb;
import com.qq.weixin.mp.message.hxexp.model.send.TextReplyJaxb;

/**
 * Java对象转换XML助手类
 *
 * @author li.jiang
 *
 */
public final class JaxbMarshallerHelper {
    private static JAXBContext context;
    private static final Class<?>[] JAXBCLASSES = { BaseReplyJaxb.class, TextReplyJaxb.class, ImageReplyJaxb.class,
            CommonParamJaxb.class, UnifiedOrderParamJaxb.class, NotifyResponseJaxb.class};

    private JaxbMarshallerHelper() {
    }

    /**
     * java对象转换成xml
     *
     * @param jaxbElement
     *            包含jaxb注解的java pojo
     * @param writer
     *            字符输出writer
     * @throws JAXBException
     * @throws TransformerFactoryConfigurationError
     * @throws TransformerException
     * @throws ParserConfigurationException
     * @throws IOException
     * @throws SAXException
     */
    public static void marshal(Object jaxbElement, Writer writer) throws JAXBException {
        if (context == null) {
            context = JAXBContext.newInstance(JAXBCLASSES);
        }

        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); // 指定XML的编码为UTF-8
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);// 指定对XML格式化输出
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); // 省略XML头声明信息
        // 将以jaxbElement为根的内容树编组到字符写入流
        marshaller.marshal(jaxbElement, writer);
    }

    /**
     * java对象转换成xml
     * @param jaxbElement 包含jaxb注解的java pojo
     * @return XML格式的字符串
     * @throws JAXBException
     * @throws IOException
     */
    public static String marshalToString(Object jaxbElement) throws JAXBException {
        StringWriter sw = new StringWriter();
        marshal(jaxbElement, sw);
        // 替换掉XML中的转义字符并返回XML字符串
        return StringHelper.replaceXMLEscapeChar(sw.toString().trim());
    }
}
